package com.carkeeper.system.service.impl;

import com.carkeeper.common.utils.PageResult;
import com.carkeeper.common.utils.Result;
import com.carkeeper.common.utils.StatusCode;
import com.carkeeper.system.dao.RoleDao;
import com.carkeeper.system.dao.UserDao;
import com.carkeeper.system.pojo.Department;
import com.carkeeper.system.pojo.Employee;
import com.carkeeper.system.pojo.Role;
import com.carkeeper.system.service.DepartmentService;
import com.carkeeper.system.service.RoleService;
import com.carkeeper.system.service.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private RoleService roleService;

    /**
     * 根据ID查询
     * 可用于修改时数据回显
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> findById(Integer id) {
        Map<String, Object> resultMap = new HashMap<>();
        Employee employee = userDao.selectByPrimaryKey(id);
        //查询到每个employee对应的role_id的集合
        List<Long> roleIds = userDao.findroleIdByemployeeId(employee.getId());
        //将role_id的集合封装到employee中
        employee.setRoleIds(roleIds);
        //获取所有部门
        List<Department> departments = departmentService.findAll();
        //获取所有角色
        List<Role> roles = roleService.findAll();
        resultMap.put("employee", employee);
        resultMap.put("departments", departments);
        resultMap.put("roles", roles);
        return resultMap;
    }


    /**
     * 修改用户
     *
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        userDao.updateByPrimaryKey(employee);
    }

    /**
     * 修改密码
     *
     * @param username
     * @param oldPassword
     * @param newPassword
     */
    @Override
    public Result changePassword(String username, String oldPassword, String newPassword) {
        Result<Object> result = new Result<>();
        //查询旧密码
        String password = userDao.findPassword(username);
        //如果密码一致,则修改密码
        if (password.equals(oldPassword)) {
            userDao.changePassword(username, newPassword);
            return new Result(true, StatusCode.OK, "修改成功");
        }
        return new Result(false, StatusCode.ERROR, "密码错误");
    }

    /**
     * 锁定/解锁
     *
     * @param employee
     */
    @Override
    public Result lock(Employee employee) {
        Result<Object> result = new Result<>();
        //锁定
        if ("0".equals(employee.getAccountStatus())) {
            employee.setAccountStatus("1");
            userDao.updateByPrimaryKey(employee);
            return new Result(true, StatusCode.OK, "锁定成功");
        } else {
            //解锁
            employee.setAccountStatus("0");
            userDao.updateByPrimaryKey(employee);
            return new Result(true, StatusCode.OK, "解锁成功");
        }
    }


    /**
     * 条件+分页查询
     *
     * @param searchMap 查询条件
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @Override
    public Map<String, Object> findPage(Map<String, Object> searchMap, int page, int size) {
        Map<String, Object> resultMap = new HashMap<>();
        //获取前端传来的搜索条件role_id
        Long roleId = (Long) searchMap.get("role_id");
        //获取所有部门
        List<Department> departments = departmentService.findAll();
        //获取所有角色
        List<Role> roles = roleService.findAll();
        Example example = createExampleForUser(searchMap);
        PageHelper.startPage(page, size);
        //进行多条件查询
        Page<Employee> pageList = (Page<Employee>) userDao.selectByExample(example);
        //创建新的list
        Page<Employee> pageListAfter = new Page<>();

        //当前台的多条件查询未选择角色
        if (roleId == null) {
            for (Employee employee : pageList) {
                //查询到每个employee对应的role_id的集合
                List<Long> roleIds = userDao.findroleIdByemployeeId(employee.getId());
                //将role_id的集合封装到employee中
                employee.setRoleIds(roleIds);
                //从员工中筛选出用户,用户名密码不为空
                if (employee.getUsername() != null && employee.getPassword() != null) {
                    //将符合条件的employee转存
                    pageListAfter.add(employee);
                }
            }
        }

        //当前台的多条件查询选择了角色
        if (roleId != null) {
            for (Employee employee : pageList) {
                //查询到每个employee对应的role_id的集合
                List<Long> roleIds = userDao.findroleIdByemployeeId(employee.getId());
                //将role_id的集合封装到employee中
                employee.setRoleIds(roleIds);
                //从员工中筛选出用户,用户名密码不为空,并且包含前端传来的roleId
                if (employee.getUsername() != null && employee.getPassword() != null && roleIds.contains(roleId)) {
                    //将符合条件的employee转存
                    pageListAfter.add(employee);
                }
            }
        }

        PageResult pageResult = new PageResult(pageListAfter.getTotal(), pageListAfter.getResult());
        resultMap.put("pageResult", pageResult);
        resultMap.put("departments", departments);
        resultMap.put("roles", roles);
        return resultMap;
    }


    /**
     * 构建查询对象
     * 员工查询
     *
     * @param searchMap
     * @return
     */
    private Example createExampleForUser(Map<String, Object> searchMap) {
        Example example = new Example(Employee.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 用户名
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andLike("username", "%" + searchMap.get("username") + "%");
            }
            // 姓名
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 手机号
            if (searchMap.get("phone") != null && !"".equals(searchMap.get("phone"))) {
                criteria.andLike("phone", "%" + searchMap.get("phone") + "%");
            }
            // 部门id
            if (searchMap.get("departmentId") != null && !"".equals(searchMap.get("departmentId"))) {
                criteria.andLike("departmentId", "%" + searchMap.get("departmentId") + "%");
            }
            // 状态
            if (searchMap.get("accountStatus") != null && !"".equals(searchMap.get("accountStatus"))) {
                criteria.andLike("accountStatus", "%" + searchMap.get("accountStatus") + "%");
            }
            // id
            if (searchMap.get("id") != null) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }
        }
        return example;
    }

}
